//
//  LEEditGoodsController.m
//  LoveExpressBusiness
//
//  Created by 刘甲奇 on 2017/5/23.
//  Copyright © 2017年 DFH. All rights reserved.
//

#import "LEEditGoodsController.h"
#import "LEGoodsBottomBar.h"
#import "LEGoodsCategoryCell.h"
#import "LEGoodsEditCell.h"
#import "LEUploadCell.h"
#import "LEOpenPickerTool.h"
#import "LEOrderGoodsModel.h"
#import "UIImageView+WebCache.h"

#import "LESelectGoodsCategoryController.h"

static NSString *const LEGoodsCategoryCellId = @"LEGoodsCategoryCell";
static NSString *const LEGoodsEditCellId = @"LEGoodsEditCell";
static NSString *const LEUploadCellId = @"LEUploadCell";

@interface LEEditGoodsController ()
/**
 点编辑后过来的商品
 */
@property(nonatomic,strong)LEOrderGoodsModel *Goodsmodel;

/**
 商品的种类信息
 */
@property(nonatomic,strong)NSDictionary *cate_name;
// 标题数组
@property(nonatomic,strong)NSArray *titleArray;
// image
@property(nonatomic,strong)UIImage *selectedImage;
/**
 上传的商品信息
 */
@property(nonatomic,strong)NSMutableDictionary *goodsInfo;


@end

@implementation LEEditGoodsController

- (void)setupUI
{
    [super setupUI];
    
    self.title = @"编辑商品";
    [self.tabBarController.tabBar setHidden:YES];
    
    LEGoodsBottomBar *bottomBar = (LEGoodsBottomBar *)[UIView getNibView:@"LEGoodsBottomBar"];
    [self.view addSubview:bottomBar];
    bottomBar.frame = CGRectMake(0,LEScreenHeight -50 -64, LEScreenWidth, 50);
    __weak typeof (self) weakSelf = self;
    [bottomBar bottomBarClick:^(NSInteger tag) {
        if (tag == 1) {
            self.Goodsmodel.g_state = @"1";
        }
        if (tag == 2) {
             self.Goodsmodel.g_state = @"0";
        }
        
        [weakSelf checkEmpty];
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LEGoodsCategoryCell" bundle:nil] forCellReuseIdentifier:LEGoodsCategoryCellId];
    [self.tableView registerNib:[UINib nibWithNibName:@"LEGoodsEditCell" bundle:nil] forCellReuseIdentifier:LEGoodsEditCellId];
    [self.tableView registerNib:[UINib nibWithNibName:@"LEUploadCell" bundle:nil] forCellReuseIdentifier:LEUploadCellId];
    
    //通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectCatgory:) name:Select_GoodsCategory_Notification object:nil];
}
- (void)loadData
{
    self.titleArray = [NSArray arrayWithObjects:@"商品名称",@"价格",@"市场价格",@"成本价",@"库存",@"支持上门", nil];
    if (self.commonid) {
        //发送请求
        [self rquestGoodsInfo];
    }
}
#pragma mark- 网络请求
- (void)rquestGoodsInfo
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.commonid forKey:@"commonid"];
    
    [SVProgressHUD showWithStatus:@"正在加载中"];
    __weak typeof (self) weakSelf = self;
    [API requestAppendKey:StoreGoodsDetialUrl params:dict success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        LELog(@"%s---%d---%@",__func__,__LINE__,successCode);
        NSDictionary *datas = successCode[@"datas"];
        NSString *error = datas[@"error"];
        if (error)
        {
            [SVProgressHUD showErrorWithStatus:error];
        }else
        {
            LEOrderGoodsModel *model = [LEOrderGoodsModel mj_objectWithKeyValues:datas[@"goodscommon_info"]];
            weakSelf.Goodsmodel = model;
            [weakSelf.tableView reloadData];
        }
        
    } falure:^(NSError *er) {
        LELog(@"%s---%d---%@",__func__,__LINE__,er);
        [SVProgressHUD dismiss];
    }];
}
/**
 请求添加商品
 */
- (void)requestAddGoods
{
    [SVProgressHUD showWithStatus:@"正在上传中"];
    __weak typeof (self) weakSelf = self;
    [API requestPostAppendKey:StoreEditGoodsUrl params:self.goodsInfo success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        LELog(@"%s---%d---%@",__func__,__LINE__,successCode);
        id datas = successCode[@"datas"];
        if ([datas isKindOfClass:[NSDictionary class]])
        {
            NSString *error = datas[@"error"];
            if (error)
            {
                [SVProgressHUD showErrorWithStatus:error];
            }
        }else if ([datas isKindOfClass:[NSString class]])
        {
            [SVProgressHUD showSuccessWithStatus:datas];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            [weakSelf addNotification];
        }
    } falure:^(NSError *er) {
        LELog(@"%s---%d---%@",__func__,__LINE__,er);
        [SVProgressHUD dismiss];
    }];
}

/**
 上传商品的图片
 */
- (void)requestUploadImage
{
    //设置参数
    NSData *data = UIImageJPEGRepresentation(self.selectedImage, 0.5);
    
    [SVProgressHUD showWithStatus:@"上传图片"];
    __weak typeof (self) weakSelf = self;
    [API netImage:StoreUploadGoodsImageUrl andData:data imageName:@"image" success:^(NSDictionary *successCode) {
        [SVProgressHUD dismiss];
        LELog(@"%s---%d---%@",__func__,__LINE__,successCode);
        id datas = successCode[@"datas"];
        if ([datas isKindOfClass:[NSDictionary class]])
        {
            NSString *error = datas[@"error"];
            if (error)
            {
                [SVProgressHUD showErrorWithStatus:error];
                return;
            }
            weakSelf.Goodsmodel.goods_image = datas[@"name"];
            
            NSIndexPath *path = [NSIndexPath indexPathForRow:7 inSection:0];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];
        }else if ([datas isKindOfClass:[NSString class]])
        {
            [SVProgressHUD showSuccessWithStatus:datas];
        }
        
    } falure:^(NSError *er) {
        [SVProgressHUD dismiss];
    }];
}

#pragma mark- privateMethod
//@"商品名称",@"价格",@"市场价格",@"成本价",@"库存",@"支持上门"
- (void)checkEmpty
{
    //商品种类
    if (!self.cate_name)
    {
        [self.goodsInfo setObject:self.Goodsmodel.gc_name forKey:@"cate_name"];
        [self.goodsInfo setObject:self.Goodsmodel.gc_id forKey:@"cate_id"];
    }else{
        [self.goodsInfo setObject:self.cate_name[@"cate_name"] forKey:@"cate_name"];
        [self.goodsInfo setObject:self.cate_name[@"cate_id"] forKey:@"cate_id"];
    }
    
    //上传图片
    [self.goodsInfo setObject:self.Goodsmodel.goods_image forKey:@"image_path"];
    
    //商品名称
    NSString *goodName = [self getFieldText:1];
    if ([goodName isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入商品名称"];
        return;
    }
    [self.goodsInfo setValue:goodName forKey:@"g_name"];
    
    //价格
    NSString *goodPrice = [self getFieldText:2];
    if ([goodPrice isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入商品价格"];
        return;
    }
    [self.goodsInfo setValue:goodPrice forKey:@"g_price"];

    //市场价格
    NSString *marketPrice = [self getFieldText:3];
    if ([marketPrice isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入市场价格"];
        return;
    }
    [self.goodsInfo setValue:marketPrice forKey:@"g_marketprice"];

    //成本价
    NSString *basicPrice = [self getFieldText:4];
    if ([basicPrice isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入成本价格"];
        return;
    }
    [self.goodsInfo setValue:basicPrice forKey:@"g_costpric"];
    float discount = [basicPrice floatValue]/[goodPrice floatValue]>1?0.0:[basicPrice floatValue]/[goodPrice floatValue];
    [self.goodsInfo setValue:[NSString stringWithFormat:@"%f",discount] forKey:@"g_discount"];

    //库存
    NSString *storage = [self getFieldText:5];
    if ([storage isEqualToString:@""])
    {
        [SVProgressHUD showInfoWithStatus:@"请输入库存"];
        return;
    }
    [self.goodsInfo setValue:storage forKey:@"g_storage"];

    //是否支持上门服务
    [self.goodsInfo setValue:self.Goodsmodel.door_service forKey:@"door_service"];
    
    //上架,还是到库存
    [self.goodsInfo setObject:self.Goodsmodel.g_state forKey:@"g_state"];
    
    //common_id
    [self.goodsInfo setObject:self.commonid forKey:@"common_id"];

    [self requestAddGoods];
}
/**
 根据行号获取输入框的内容
 
 @param indexPathRow <#indexPathRow description#>
 @return <#return value description#>
 */
- (NSString *)getFieldText:(NSInteger)indexPathRow
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:indexPathRow inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
    if ([cell isKindOfClass:[LEGoodsEditCell class]])
    {
        LEGoodsEditCell *cells = (LEGoodsEditCell *)cell;
        return  cells.inputField.text;
    }
    return @"";
}
/**
 添加通知,告诉审核控制器,和仓库控制器刷新
 */
- (void)addNotification
{
    NSString *isCheck = self.goodsInfo[@"g_state"];
    //1--上架
    if ([isCheck isEqualToString:@"1"])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:AddGoods_Check_Notification object:nil];
        
    }else if ([isCheck isEqualToString:@"0"])
    {
        //0 --仓库
        [[NSNotificationCenter defaultCenter] postNotificationName:AddGoods_Storage_Notification object:nil];
    }
    
}
#pragma mark- tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        LEGoodsCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:LEGoodsCategoryCellId forIndexPath:indexPath];
        if (self.cate_name) {
            cell.goodsCategoryLabel.text = self.cate_name[@"cate_name"];
            return cell;
        }
        if (self.Goodsmodel) {
            cell.goodsCategoryLabel.text = self.Goodsmodel.gc_name;
        }
        return cell;
    }
    if (indexPath.row == 7)
    {
        LEUploadCell *cell = [tableView dequeueReusableCellWithIdentifier:LEUploadCellId forIndexPath:indexPath];
        [cell.upLoadButton addTarget:self action:@selector(uploadClick:) forControlEvents:UIControlEventTouchUpInside];
        if (self.selectedImage) {
            cell.uploadedIV.image = self.selectedImage;
            return cell;
        }
        
        if (self.Goodsmodel) {
            [cell.uploadedIV sd_setImageWithURL:[NSURL URLWithString:self.Goodsmodel.image_path]];
        }
        return cell;
    }
    
    LEGoodsEditCell *cell = [tableView dequeueReusableCellWithIdentifier:LEGoodsEditCellId forIndexPath:indexPath];
    cell.titleLabel.text = self.titleArray[indexPath.row -1];
    cell.chectButton.hidden = YES;
    cell.inputField.hidden = NO;
    if (self.Goodsmodel)
    {
        switch (indexPath.row) {
            case 1:
                cell.inputField.text = self.Goodsmodel.goods_name;
                break;
            case 2:
                cell.inputField.text = self.Goodsmodel.goods_price;
                break;
            case 3:
                cell.inputField.text = self.Goodsmodel.goods_marketprice;
                break;
            case 4:
                cell.inputField.text = self.Goodsmodel.goods_costprice;
                break;
            case 5:
                cell.inputField.text = self.Goodsmodel.g_storage;
                break;
                
            default:
                break;
        }
        
    }else{
        cell.inputField.placeholder = [NSString stringWithFormat:@"请输入%@",self.titleArray[indexPath.row -1]];
    }
    //设置键盘样式
    if (indexPath.row == 1)
    {
        cell.inputField.keyboardType = UIKeyboardTypeDefault;
    }else{
        cell.inputField.keyboardType = UIKeyboardTypeNumberPad;
    }
    
    if (indexPath.row == 6) {
        cell.chectButton.hidden = NO;
        [cell.chectButton addTarget:self action:@selector(supportClick:) forControlEvents:UIControlEventTouchUpInside];
        UIImage *shouldImage = [self.Goodsmodel.door_service integerValue]?[UIImage imageNamed:@"goods_selected"]:[UIImage imageNamed:@"goods_chectBox"];
        [cell.chectButton setImage:shouldImage forState:0];
        cell.inputField.hidden = YES;
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        LESelectGoodsCategoryController *select = [[LESelectGoodsCategoryController alloc] init];
        [self.navigationController pushViewController:select animated:YES];
    }
}
#pragma mark- 点击事件
- (void)supportClick:(UIButton *)sender
{
    self.Goodsmodel.door_service = [self.Goodsmodel.door_service intValue] ? @"0" : @"1";
    NSIndexPath *path = [NSIndexPath indexPathForRow:6 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationFade];
    
}
- (void)uploadClick:(UIButton *)sender
{
    LELog(@"%s---%d---点击上产图片",__func__,__LINE__);
    dispatch_async(dispatch_get_main_queue(), ^{
        [LEOpenPickerTool openPickerView:self];
    });
}
/**
 选择好商品的种类的通知
 
 @param notification <#notification description#>
 */
- (void)selectCatgory:(NSNotification *)notification
{
    LELog(@"%s---%d---%@",__func__,__LINE__,notification);
    self.cate_name = notification.object;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
}
#pragma mark- imagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        self.selectedImage = image;
        [self requestUploadImage];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark- getter
- (NSMutableDictionary *)goodsInfo
{
    if (_goodsInfo == nil) {
        _goodsInfo = [NSMutableDictionary dictionary];
    }
    return _goodsInfo;
}
@end
